<template>
  <div class="show_area">
    <input type="button" value="请求数据" @click="getData" />
    <input type="button" value="重新加载" @click="PicEchartA" />
    <div id="theA" style="width: 100%; height: 800px"></div>
  </div>
</template>
<script>
// import { defineComponent } from '@vue/composition-api'
import * as echarts from "echarts";
import axios from "axios";
import  CryptoJS from "crypto-js";
import {generateAuthorization}  from "../assets/pre_request.js";
import {useOfflineData} from '../assets/offline-data.js';


export default {
  name: "express Api",
  data() {
    var data = {
      data_all:[],
      top_10_serious: [], //前10 严重
      // ,data_full: []
      coffee_data: [],
      coffee_checkData: [],
      data_time:''
    };
    return data;
  },
  created() {
    const apiA_method = 'GET';
    const apiA_host = "rankcity.api.bdymkt.com";
    const apiA_path = "baiduapi"; 
    const apiA_query = "";
    const apiA_header = { 'host':"rankcity.api.bdymkt.com",'content-type':'application/json;charset=utf-8' }; //'host':"rankcity.api.bdymkt.com"
    const apiA_signHeader = 'host;content-type';
    

    const requireB = axios.create({
      baseURL: ""
    });

    requireB.interceptors.request.use(
      config =>{ //添加认证
        config.headers['X-Bce-Signature']=
          `${generateAuthorization(apiA_method,apiA_path,apiA_query,apiA_header,apiA_signHeader)}`;
        console.log(config);
        return config;
      },
      error =>{
        return Promise.reject(error);
      }
    );
    requireB({
      methods:apiA_method,
      url:'/'+apiA_path,
      headers:{ 'content-type':'application/json;charset=utf-8'}
    })
    .catch(function (error) {
    if (error.response) {
      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      console.log('Error', error.message);
    }
    console.log(error.config);
  }).then((res) => {
    if (res) {
      console.log(res, "res", isNaN(res));
      this.data_all = res['data']['list'];
      this.data_time = ' 数据统计日期:'+res['data']['update_time'];
    }
    else{
      var that = this;
      var offline_data = useOfflineData();
      console.log(offline_data,'离线数据')
      this.data_all=offline_data['list'];
      this.data_time = ' 数据日期:'+offline_data['update_time'];
      // this.data_all=offline_data['list'];
    }
    console.log(this.data_all,'请求完毕',isNaN(this.data_all));
    });
  },
  mounted() {
    var that = this;
    setTimeout(() => {
      this.dataLoad();
      this.PicEchartA();
      console.log('数据加载完毕')
    }, 1000);
  },
  methods: {
    dataLoad() {
      var that = this;
      for (let i = 0; i < 10; i++) {
          let item = [that.data_all[i]['province']+'-'+that.data_all[i]['city'] + '\n' + that.data_all[i]['aqi_level'],that.data_all[i]['aqi'],that.data_all[i]['aqi_level']];
          that.top_10_serious.push(item);
        }
      //处理过程用函数封装
      // function SelectTop() {
        
      // }
      // SelectTop();
      // 每隔数毫秒加载数据
      // var check = 0;
      // var data_loader =  setInterval(() => {
      //   if (check > 30) {
      //     clearInterval(data_loader);
      //   }
      //   if (typeof(that.data_all) == undefined) {
      //     SelectTop();
      //     console.log("data 404",this.data_all);
      //   } else {
      //     console.log("data 404",this.data_all,check);
      //     check += 1;
      //   }
      // }, 400);

    },
    PicEchartA() {
      var that = this;
      var chartC = echarts.init(document.getElementById("theA"));
      // console.log(this.data_part, "检验");
      var option = {
        title: {
          text: "全国城市污染程度TOP10"+that.data_time,
          top: "3%",
          left: "center",
          textStyle: { fontSize: 18 },
        },
        legend: {},
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          // grid: [
          //   { bottom: 61, left: "center" },
          //   { height: 60, bottom: 0, left: "center" },
          // ],
          // position: function (pos, params, el, elRect, size) {
          //   var obj = { top: 10 };
          //   obj[["left", "right"][+(pos[0] < size.viewSize[0] / 2)]] = 30;
          //   return obj;
          // },
          extraCssText: "width: 300px", //个体信息框宽度
        },
        dataset: {
          source: that.top_10_serious,
          dimensions: ["city", "aqi","aqi_level"],
        },
        xAxis: {
          type: "category",
          name: "城市",
          axisLabel: {
            interval: 0, //轴刻度标签全部显示
          },
        },
        yAxis: {
          type: "value",
          name:'污染指数'
        },
        series: [
          {
            type: "bar",
            name: "AQI污染程度",
          },
          {
            type: "line",
            name: "aqi_level",
          }
        ],
      };

      var that = this; // 缓存指针
      chartC.setOption(option);
      // 每隔数毫秒应用配置项
      // var echart_creater =  setInterval(() => {
      //   if (isNaN(that.top_10_serious)) {
      //     chartC.setOption(option);
      //     clearInterval(echart_creater);
      //   } else {
      //     console.log("data not found",that.top_10_serious);
      //   }
      // }, 400);

      // 延迟数毫秒后应用配置项
      /*
      setTimeout(function () {
        // console.log("set内", that.data_part, "this指向", this.data_part);
        if (isNaN(that.data_part)) {
          // console.log("set>if内", that.data_part, "this指向", this.data_part);

          chartC.setOption(option);
        } else {
          console.log("data not found");
        }
      }, 400);
      */
    },
  },
};
</script>